﻿@page "/So/SaleReturn/Create"
@using nERP.ViewModel.So.SaleReturnVMs
@using nERP.Model.So
@using System.ComponentModel.DataAnnotations
@inherits BasePage

<div>
    <ValidateForm @ref="vform" Model="@Model" OnValidSubmit="@Submit">
        <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Normal">
            <BootstrapInputGroupLabel @bind-Value="@Model.Entity.SaleReturnCode" />
            <BootstrapInputGroup>
                <BootstrapInput @bind-Value="@Model.Entity.SaleReturnCode"></BootstrapInput>
                <Button @ref="@btnSN" Icon="fas fa-plus" Text="@WtmBlazor.Localizer["Page.生成号码"]" OnClick="OnCreateSNAsync"></Button>
            </BootstrapInputGroup>
            <Select @bind-Value="@Model.Entity.SaleOutWarehouseId" Items="AllSaleOutWarehouses" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" IsPopover ShowSearch OnSelectedItemChanged="OnSelectedItemChanged" />
            <Select @bind-Value="@Model.Entity.SaleId" Items="AllSales" />
            <Select @bind-Value="@Model.Entity.CustomerId" Items="AllCustomers" />
            <DateTimePicker @bind-Value="@Model.Entity.InvoicesDate" />
            <Select @bind-Value="@Model.Entity.MakeUserId" Items="AllMakeUsers" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" IsPopover ShowSearch />
            <BootstrapInput @bind-Value="@Model.Entity.Remark" />
            <WTUploadImage @bind-Value="@Model.Entity.InvoicesFile" />
        </Row>
        <Divider Icon="fa-fw fa-solid fa-bookmark" Text="@WtmBlazor.Localizer["_Model._SaleReturn._SaleReturnDetail_SaleReturn"]" Alignment="Alignment.Left" />


        <Table TItem="SaleReturnDetail" @bind-Items="@SaleReturnDetailSaleReturnList" OnDeleteAsync="@OnDeleteAsync" ShowFooter="true" ShowAddButton="false"
               ShowSkeleton="true" IsStriped="true" IsBordered="true" ShowRefresh="false" ShowToolbar="true" ShowExtendButtons="true" IsExcel="true">
            <TableColumns>
                <TableColumn @bind-Field="@context.Seq" Text="@WtmBlazor.Localizer["Page.序号"]" Readonly="true" />
                <TableColumn @bind-Field="@context.SaleReturnDetailCode" Text="@WtmBlazor.Localizer["Page.退货明细单号"]" Visible="false" />
                <TableColumn @bind-Field="@context.SaleOutWarehouseDetailId" Text="@WtmBlazor.Localizer["Page.销售出库明细"]" Visible="false" />
                <TableColumn @bind-Field="@context.GoodsId" Text="@WtmBlazor.Localizer["Page.商品编号"]" Readonly="true" />
                <TableColumn @bind-Field="@context.GoodsName" Text="@WtmBlazor.Localizer["Page.商品名称"]" Readonly="true" />
                <TableColumn @bind-Field="@context.GoodsSpec" Text="@WtmBlazor.Localizer["Page.商品规格"]" Readonly="true" />
                <TableColumn @bind-Field="@context.GoodsUnit" Text="@WtmBlazor.Localizer["Page.商品单位"]" Readonly="true" />
                <TableColumn @bind-Field="@context.ReturnNumber" Text="@WtmBlazor.Localizer["Page.退货数量"]">
                    <EditTemplate Context="V">
                        <BootstrapInput @bind-Value="V.ReturnNumber" @onfocusout="()=>Input_OnFocusout(V)" />
                    </EditTemplate>
                </TableColumn>
                <TableColumn @bind-Field="@context.UnitPrice" Text="@WtmBlazor.Localizer["Page.退货单价"]">
                    <EditTemplate Context="V">
                        <BootstrapInput @bind-Value="V.UnitPrice" @onfocusout="()=>Input_OnFocusout(V)" />
                    </EditTemplate>
                </TableColumn> @* 不含税单价 *@
                <TableColumn @bind-Field="@context.TotalPrice" Text="@WtmBlazor.Localizer["Page.退货金额"]" Readonly="true" />
                <TableColumn @bind-Field="@context.DiscountPrice" Text="@WtmBlazor.Localizer["Page.折扣金额"]">
                    <EditTemplate Context="V">
                        <BootstrapInput @bind-Value="V.DiscountPrice" @onfocusout="()=>Input_OnFocusout(V)" />
                    </EditTemplate>
                </TableColumn> @* 折扣金额 默认=金额 *@
                <TableColumn @bind-Field="@context.TaxRate" Text="@WtmBlazor.Localizer["Page.税率"]">
                    <EditTemplate Context="V">
                        <BootstrapInput @bind-Value="V.TaxRate" @onfocusout="()=>Input_OnFocusout(V)" />
                    </EditTemplate>
                </TableColumn>
                <TableColumn @bind-Field="@context.TaxUnitPrice" Text="@WtmBlazor.Localizer["Page.含税单价"]" Readonly="true" />
                <TableColumn @bind-Field="@context.TaxPrice" Text="@WtmBlazor.Localizer["Page.税额"]" Readonly="true" />
                <TableColumn @bind-Field="@context.TotalTaxPrice" Text="@WtmBlazor.Localizer["Page.含税金额"]" Readonly="true" />
                <TableColumn @bind-Field="@context.Remark" Text="@WtmBlazor.Localizer["_Admin.Remark"]" />
            </TableColumns>

            <TableToolbarTemplate>
                <TableToolbarButton TItem="SaleReturnDetail" Color="Color.Primary" Icon="fa-fw fa-solid fa-pen-to-square" Text="@WtmBlazor.Localizer["Sys.Select"]" OnClickCallback="@ShowDialog" IsDisabled="@string.IsNullOrEmpty(Model.Entity.SaleOutWarehouseId)" />
                <Modal @ref="GoodsModal">
                    <ModalDialog Title="选择商品" IsCentered IsDraggable="true">
                        <BodyTemplate>
                            <Table TItem="nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetail_View" @ref="GoodsTable" IsStriped="true" @bind-SelectedRows="@SelectedRows"
                                   ShowToolbar="true" ShowDefaultButtons="false" IsMultipleSelect="true" ClickToSelect="true" OnQueryAsync="SaleOutWarehouseDetailListVMOnSearchSaleOutWarehouseDetail"
                                   AllowResizing="true" IsPagination="true" AllowDragColumn="true" ShowColumnList="true" ShowSearch="false" SearchTooltip=""
                                   OnResetSearchAsync="OnResetSearchAsync" SearchMode="SearchMode.Top" CollapsedTopSearch="true" ShowSearchText="false">
                                @* <SearchTemplate>
                                <ValidateForm Model="@Model2">
                                <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Inline">
                                <Select @bind-Value="@Model2.Searcher.SaleId" Items="AllSales" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]" />
                                </Row>
                                </ValidateForm>
                                </SearchTemplate> *@
                                <TableColumns>
                                    <TableColumn @bind-Field="@context.SaleOutWarehouseDetail_SaleOutWarehouseDetailCode" Text="@WtmBlazor.Localizer["Page.销售出库明细单号"]" />
                                    <TableColumn @bind-Field="@context.SaleOutWarehouseDetail_Goods" Text="@WtmBlazor.Localizer["Page.商品"]" />
                                    <TableColumn @bind-Field="@context.SaleOutWarehouseDetail_GoodsName" Text="@WtmBlazor.Localizer["Page.商品名称"]" />
                                    <TableColumn @bind-Field="@context.SaleOutWarehouseDetail_GoodsSpec" Text="@WtmBlazor.Localizer["Page.商品规格"]" />
                                    <TableColumn @bind-Field="@context.SaleOutWarehouseDetail_GoodsUnit" Text="@WtmBlazor.Localizer["Page.商品单位"]" />
                                    <TableColumn @bind-Field="@context.SaleOutWarehouseDetail_SaleOutNumber" Text="@WtmBlazor.Localizer["Page.数量"]" />
                                    <TableColumn @bind-Field="@context.SaleDetail_UnitPrice" Text="@WtmBlazor.Localizer["Page.单价"]" />
                                    <TableColumn @bind-Field="@context.SaleDetail_TotalPrice" Text="@WtmBlazor.Localizer["Page.金额"]" />
                                    <TableColumn @bind-Field="@context.SaleDetail_DiscountPrice" Text="@WtmBlazor.Localizer["Page.折扣金额"]" />
                                    <TableColumn @bind-Field="@context.SaleDetail_TaxRate" Text="@WtmBlazor.Localizer["Page.税率"]" />
                                    <TableColumn @bind-Field="@context.SaleDetail_TaxUnitPrice" Text="@WtmBlazor.Localizer["Page.含税单价"]" />
                                    <TableColumn @bind-Field="@context.SaleDetail_TaxPrice" Text="@WtmBlazor.Localizer["Page.税额"]" />
                                    <TableColumn @bind-Field="@context.SaleDetail_TotalTaxPrice" Text="@WtmBlazor.Localizer["Page.含税金额"]" />
                                </TableColumns>
                            </Table>
                        </BodyTemplate>
                        <FooterTemplate>
                            <Button Text="@WtmBlazor.Localizer["Sys.OK"]" Icon="fa-regular fa-square-check" OnClick="@OnConfirm" />
                        </FooterTemplate>
                    </ModalDialog>
                </Modal>
            </TableToolbarTemplate>
            <FooterTemplate>
                <tr style="background-color:gray; font-weight:600; text-align:center;">
                    <td colspan="6">合计：</td>
                    <td>@sumReturnNumber</td>
                    <td colspan="1" />
                    <td>@sumTotalPrice</td>
                    <td style="color:red;">@sumDiscountPrice</td>
                    <td colspan="2" />
                    <td> @sumTaxPrice</td>
                    <td> @sumTotalTaxPrice</td>
                </tr>
            </FooterTemplate>
        </Table>

        <div class="modal-footer table-modal-footer">
            <Button ButtonType="ButtonType.Submit" IsAsync="true" Text="@WtmBlazor.Localizer["Sys.Submit"]" />
            <Button OnClick="OnClose" Text="@WtmBlazor.Localizer["Sys.Close"]" />
        </div>

    </ValidateForm>

</div>



@code {
    [Parameter]
    public string id { get; set; }
    [Parameter]
    public string[] ids { get; set; }
    private SaleReturnVM Model = new SaleReturnVM();
    private ValidateForm vform { get; set; }
    private string sumReturnNumber { get; set; }
    private string sumTotalPrice { get; set; }
    private string sumDiscountPrice { get; set; }
    private string sumTaxPrice { get; set; }
    private string sumTotalTaxPrice { get; set; }
    private async Task Submit(EditContext context)
    {

        Model.Entity.SaleReturnDetail_SaleReturn = SaleReturnDetailSaleReturnList.ToList();
        Model.Entity.SaleReturnDetail_SaleReturn.ForEach(x => x.SaleReturnDetailCode = Model.Entity.SaleReturnCode + x.Seq.ToString());
        Model.Entity.TotalPrice = Model.Entity.SaleReturnDetail_SaleReturn.Any() ? Model.Entity.SaleReturnDetail_SaleReturn.Sum(x => x.DiscountPrice) : 0;

        await PostsForm(vform, "/api/So/SaleReturn/Create", (s) => "Sys.OprationSuccess");
    }
    public void OnClose()
    {
        CloseDialog();
    }

    private List<SelectedItem> AllSaleOutWarehouses = new List<SelectedItem>();
    private List<SelectedItem> AllSales = new List<SelectedItem>();
    private List<SelectedItem> AllCustomers = new List<SelectedItem>();
    private List<SelectedItem> AllMakeUsers = new List<SelectedItem>();
    private IEnumerable<SaleReturnDetail> SaleReturnDetailSaleReturnList { get; set; } = new List<SaleReturnDetail>();
    private List<SaleReturnDetail> Items { get; set; } = new List<SaleReturnDetail>();
    protected override async Task OnInitializedAsync()
    {


        AllSaleOutWarehouses = await WtmBlazor.Api.CallItemsApi("/api/So/SaleReturn/GetSaleOutWarehouses");
        AllSaleOutWarehouses.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });
        // AllSales = await WtmBlazor.Api.CallItemsApi("/api/So/SaleReturn/GetSales");
        // AllSales.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });
        AllMakeUsers = await WtmBlazor.Api.CallItemsApi("/api/So/SaleReturn/GetFrameworkUsers");
        AllMakeUsers.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });

        Model.Entity.InvoicesDate = DateTime.Now;
        Model.Entity.Status = nERP.Model.StatusTypeEnum.Unaudited;
        Model.Entity.MakeUserId = UserInfo.ITCode;

        await base.OnInitializedAsync();
    }

    private Button btnSN { get; set; }
    private async Task OnCreateSNAsync(MouseEventArgs e)
    {
        var SN = await GetNewSN2("销售退货", false);
        Model.Entity.SaleReturnCode = SN;
        btnSN.SetDisable(true);
    }

    private Task<bool> OnDeleteAsync(IEnumerable<SaleReturnDetail> items)
    {
        items.ToList().ForEach(i => Items.Remove(i));

        sums();

        //Model.Entity.TotalPrice = Items.Any() ? Items.Sum(x => x.DiscountPrice) : 0;

        return Task.FromResult(true);
    }
    private async Task OnSelectedItemChanged(SelectedItem item)
    {
        AllSales = await WtmBlazor.Api.CallItemsApi($"/api/So/SaleReturn/GetSales?SaleOutWarehouseCode={item.Value}");
        AllCustomers = await WtmBlazor.Api.CallItemsApi($"/api/So/SaleReturn/GetCustomers?SaleOutWarehouseCode={item.Value}");

        await GoodsTable.QueryAsync();

        Items = new List<SaleReturnDetail>();
        SaleReturnDetailSaleReturnList = Items;

        sums();

        StateHasChanged();
    }


    [System.Diagnostics.CodeAnalysis.NotNull]
    private Modal? GoodsModal { get; set; }
    private List<nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetail_View> SelectedRows { get; set; } = [];

    private List<SelectedItem> AllGoodsTypes = new List<SelectedItem>();

    private nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetailListVM Model2 = new ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetailListVM();

    private Task OnResetSearchAsync(nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetail_View item)
    {
        Model2.Searcher = new nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetailSearcher();
        item = new nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetail_View();
        return Task.CompletedTask;
    }
    private async Task<QueryData<nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetail_View>> SaleOutWarehouseDetailListVMOnSearchSaleOutWarehouseDetail(QueryPageOptions opts)
    {
        if (string.IsNullOrWhiteSpace(Model.Entity.SaleOutWarehouseId)) return null;

        Model2.Searcher.SaleOutWarehouseId = Model.Entity.SaleOutWarehouseId;
        return await StartSearch<nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetail_View>("/api/Wms/SaleOutWarehouseDetail/SearchSaleOutWarehouseDetail", Model2.Searcher, opts);
    }

    private Task ShowDialog(IEnumerable<SaleReturnDetail> items) => GoodsModal.Toggle();

    [System.Diagnostics.CodeAnalysis.NotNull]
    private Table<nERP.ViewModel.Wms.SaleOutWarehouseDetailVMs.SaleOutWarehouseDetail_View>? GoodsTable { get; set; }

    private async Task OnConfirm()
    {
        if (SelectedRows.Count > 0)
        {
            var newSR = SelectedRows.Where(x => !Items.Select(i => i.GoodsId).Contains(x.SaleOutWarehouseDetail_Goods)).ToList();

            foreach (var r in newSR)
            {
                var cr = new SaleReturnDetail()
                    {
                        ID = Guid.NewGuid(),
                        Seq = (Items.Max(s => s.Seq) ?? 0) + 1,
                        SaleOutWarehouseDetailId = r.SaleOutWarehouseDetail_SaleOutWarehouseDetailCode,
                        SaleId = r.SaleOutWarehouseDetail_Sale,
                        SaleDetailId = r.SaleOutWarehouseDetail_SaleDetail,
                        GoodsId = r.SaleOutWarehouseDetail_Goods,
                        GoodsName = r.SaleOutWarehouseDetail_GoodsName,
                        GoodsSpec = r.SaleOutWarehouseDetail_GoodsSpec,
                        GoodsUnit = r.SaleOutWarehouseDetail_GoodsUnit,
                        ReturnNumber = r.SaleOutWarehouseDetail_SaleOutNumber,
                        UnitPrice = r.SaleDetail_UnitPrice,
                        TotalPrice = r.SaleDetail_TotalPrice,
                        DiscountPrice = r.SaleDetail_DiscountPrice,
                        TaxRate = r.SaleDetail_TaxRate,
                        TaxUnitPrice = r.SaleDetail_TaxUnitPrice,
                        TaxPrice = r.SaleDetail_TaxPrice,
                        TotalTaxPrice = r.SaleDetail_TotalTaxPrice
                    };

                Items.Insert(Items.Count, cr);
                SaleReturnDetailSaleReturnList = Items;
            }
            sums();
        }
        StateHasChanged();

        await GoodsModal.Toggle();
    }
    private void Input_OnFocusout(SaleReturnDetail V)
    {
        if (V.ReturnNumber == null || V.ReturnNumber <= 0) { V.ReturnNumber = 0; }
        if (V.ReturnNumber > 0)
        {
            if (V.UnitPrice == null || V.UnitPrice <= 0) { V.UnitPrice = 0; }
            V.TotalPrice = V.UnitPrice * V.ReturnNumber;
            if (V.DiscountPrice == null || V.DiscountPrice <= 0) { V.DiscountPrice = V.TotalPrice; }
            if (V.TaxRate == null || V.TaxRate <= 0) { V.TaxRate = 0; }
            V.TaxUnitPrice = V.DiscountPrice / V.ReturnNumber * (1 + V.TaxRate / 100);
            V.TotalTaxPrice = V.TaxUnitPrice * V.ReturnNumber;
            V.TaxPrice = V.TotalTaxPrice / (1 + V.TaxRate / 100) * (V.TaxRate / 100);
        }

        sums();

        //Model.Entity.TotalPrice = Items.Any() ? Items.Sum(x => x.DiscountPrice) : 0;

    }
    /// <summary>
    /// 设置合计项
    /// </summary>
    private void sums()
    {
        sumReturnNumber = Items.Any() ? Items.Sum(x => x.ReturnNumber)?.ToString("#0.####") : "0";
        sumTotalPrice = Items.Any() ? Items.Sum(x => x.TotalPrice)?.ToString("#0.####") : "0";
        sumDiscountPrice = Items.Any() ? Items.Sum(x => x.DiscountPrice)?.ToString("#0.####") : "0";
        sumTaxPrice = Items.Any() ? Items.Sum(x => x.TaxPrice)?.ToString("#0.####") : "0";
        sumTotalTaxPrice = Items.Any() ? Items.Sum(x => x.TotalTaxPrice)?.ToString("#0.####") : "0";
    }
}
